import mx.events.MenuEvent;
import mx.events.ItemClickEvent;
import mx.events.VideoEvent; 
import mx.events.SliderEvent;
import mx.events.ListEvent;
import mx.events.DragEvent;
import mx.collections.XMLListCollection;
import mx.utils.ObjectProxy;
import mx.managers.PopUpManager;
import mx.containers.TitleWindow;
import com.globalwave.filemanage.RemotingConnection;
import com.globalwave.filemanage.SoundPlayer;


import com.globalwave.filemanage.view.rename;
import com.globalwave.filemanage.view.createFolder;


[Bindable]
public var fileData:Array; //files in current directory
[Bindable]
public var folderTree:XML; //folders available
//[Bindable]
//public var selectedNode:Object; //selected
[Bindable]
public var menuBarCollection:XMLListCollection;
    			
public var mp3player:SoundPlayer = new SoundPlayer();
    
            private var menubarXML:XMLList =
                <>
                	<menuitem label="Folder">
                        <menuitem label="Create" data="foldercreate"/>
                        <menuitem label="Delete" data="folderdelete"/>
                        <!--<menuitem label="Rename" data="folderrename"/>
                        <menuitem label="Move" data="foldermove"/>-->
                    </menuitem>
                    <menuitem label="File">
                        <menuitem label="Upload" data="upload"/>
                        <menuitem label="Download" data="download"/>
                        <menuitem label="Delete" data="delete"/>
                        <menuitem label="Rename" data="rename"/>
                    </menuitem>
                    <menuitem label="Edit">
                        <!--<menuitem label="Cut" data="cut"/>
                        <menuitem label="Copy" data="copy"/>
                        <menuitem label="Paste" data="paste"/>
                        <menuitem type="separator" />
                        <menuitem label="Copy to folder" data="copyfolder"/>
                        <menuitem label="Move to folder" data="movefolder"/>
                        <menuitem type="separator" />-->
                        <menuitem label="Select All" data="selectall"/>
                        <menuitem label="Invert Selection" data="selectinvert"/>
                    </menuitem>
                    <menuitem label="View">
                        <menuitem label="Toolbars"  data="toolbars">
                        	<menuitem label="Filter" type="check" toggled="true" data="filter"/>
                        	<menuitem label="View" type="check" toggled="true"  data="view"/>
                        	<menuitem label="Zoom" type="check" toggled="true"  data="zoom"/>
                        </menuitem>
                        <menuitem type="separator" />
                        <menuitem label="Thumbnails" toggled="true" type="radio"  data="thumbnails"/>
                        <menuitem label="Details" type="radio"  data="details"/>
                        <menuitem type="separator" />
						<menuitem label="Refresh"  data="refresh"/>
                    </menuitem>
                </>;
                
                [Bindable]
                public var display: Array = [ 
                {label:"Thumbnails", data:"thumbnails", toggled:true}, 
                {label:"Details", data:"details"} 
                ];

                


            public var gateway : RemotingConnection;
			public var vidcanseek:Boolean;

            public function initApplication():void
            {
                gateway = new RemotingConnection( "http://flexfm.castlesblog.com/amfphp/gateway.php");
                gateway.call( "files.getFolders", new Responder(onFolderResult, onFault));  
                menuBarCollection = new XMLListCollection(menubarXML);
                playpause.dataProvider = ["Pause","Stop"];
            }
            
            private function filterFiles():void {
            	var search:String = filter.text;
				var filterData:Object = fileData;
				var newData:Array = new Array();
				for(var i:int; i<fileData.length; i++) {
					var filename:String = fileData[i].name;//.slice(0,-3) to remove extension;
					if(filename.indexOf(search) != -1) {
						newData.push(fileData[i]);
					}
				}
				files.dataProvider = newData;
				fileTile.dataProvider = newData;
            }
            
            private function upload():void{
       			var imageTypes:FileFilter = new FileFilter("Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg; *.jpeg; *.gif; *.png");
				var textTypes:FileFilter = new FileFilter("Text Files (*.txt, *.rtf)", "*.txt; *.rtf");
				var videoTypes:FileFilter = new FileFilter("Video Files (*.flv, *.avi, *.mov)", "*.flv; *.avi; *.mov");
				var allTypes:Array = new Array(imageTypes, textTypes, videoTypes);
				var fileRef:FileReference = new FileReference();
				fileRef.addEventListener(Event.SELECT, selectHandler);
				fileRef.addEventListener(Event.COMPLETE, completeHandler);
				fileRef.addEventListener(ProgressEvent.PROGRESS, progressHandler);
				try {
				    var success:Boolean = fileRef.browse();
				} catch (error:Error) {
				    trace("Unable to browse for files.");
				}
				function selectHandler(event:Event):void {
				    var request:URLRequest = new URLRequest("http://flexfm.castlesblog.com/upload.php")
				    var params:URLVariables = new URLVariables();
    				params.folder = foldertree.selectedItem.@path;
    				trace(params.folder);
    				request.method = URLRequestMethod.POST;
					request.data = params;
				    try {
				        fileRef.upload(request);
				        pb.setProgress(0, 100);
				    } catch (error:Error) {
				        trace("Unable to upload file.");
				    }
				}
				function completeHandler(event:Event):void {
					 trace("uploaded");
					 pb.mode = "event";
					 var columns:Array = new Array("name","size","type","modified");
					 var folder:String = foldertree.selectedItem.@path;
					gateway.call( "files.getFiles", new Responder(onFileResult, onFault),folder,columns);
					 
				}		
				function progressHandler(event:ProgressEvent):void {
		            var file:FileReference = FileReference(event.target);
		            trace("progressHandler: name=" + file.name + " bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal);
		       		pb.mode = "manual";
		       		pb.setProgress(event.bytesLoaded, event.bytesTotal);
		        }
            }
          	private function download(file:String):void{
       			var request:URLRequest = new URLRequest(file);
				var fileRef:FileReference = new FileReference();
				fileRef.addEventListener(Event.COMPLETE, completeHandler);
				fileRef.addEventListener(ProgressEvent.PROGRESS, progressHandler);
				
				try {
				    fileRef.download(request);
				    pb.mode = "manual";
				    pb.setProgress(0, 100);
				} catch (error:Error) {
				    trace("Unable to browse for files.");
				}
				function completeHandler(event:Event):void {
					 trace("downloaded");
					 pb.mode = "event";
				}		
				function progressHandler(event:ProgressEvent):void {
		            var file:FileReference = FileReference(event.target);
		            trace("progressHandler: name=" + file.name + " bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal);
		       	
		       		pb.setProgress(event.bytesLoaded, event.bytesTotal);
		        }
            }
            
            private function menuHandler(event:MenuEvent):void  {
            	var data:String = event.item.@data;
            	switch(data) {
            		case 'upload':
						upload();
            			break;
            		case 'download':
            			if(fileTile.includeInLayout == true) {
            				download("http://flexfm.castlesblog.com/data/"+fileTile.selectedItem.path);
            			} else {
            				download("http://flexfm.castlesblog.com/data/"+files.selectedItem.path);
            			}
						break;
            		case 'filter':
            			if(event.item.@toggled=='true') { //casting won't seem to work?
	            			filterbox.includeInLayout = true;  
	            			filterbox.visible = true;
	            		} else {
	            			filterbox.includeInLayout = false;
	            			filterbox.visible = false;
	            		}
            			break;
            		case 'zoom':
            			if(event.item.@toggled=='true') {
	            			zoom.includeInLayout = true;  
	            		} else {
	            			zoom.includeInLayout = false;
	            		}
            			break;
            		case 'view':
            			if(event.item.@toggled=='true') {
	            			viewcombo.includeInLayout = true; 
	            			viewcombo.visible = true; 
	            		} else {
	            			viewcombo.includeInLayout = false;
	            			viewcombo.visible = false;
	            		}
            			break;
            		case 'details':
            			if(event.item.@toggled=='true') { //casting won't seem to work?
	            			fileTile.includeInLayout = false;  
	            			files.includeInLayout = true;  
	            			changeDisplay.selectedIndex = 1;
	            				            	files.visible = true;
	            	fileTile.visible = false;
	            		} 
            			break;
            		case 'thumbnails':
            			if(event.item.@toggled=='true') { //casting won't seem to work?
	            			fileTile.includeInLayout = true;  
	            			files.includeInLayout = false;  
	            			changeDisplay.selectedIndex = 0;
	            			files.visible = false;
	            			fileTile.visible = true;
	            		}
            			break;
            		case 'selectall':
            			var selectArray:Array = [];
            			var i:Number=0;
            			var found:Boolean;
            			var j:Number;
            			if(event.item.@toggled=='true') { //casting won't seem to work?
	            			if(fileTile.includeInLayout == true) {  
		            			for(i=0;i<fileTile.dataProvider.length;i++){
		            				selectArray.push(fileTile.dataProvider[i]);
		            			}
		            			fileTile.selectedItems = selectArray;
	            			}
	            			if(files.includeInLayout == true) {  
		            			for(i=0;i<files.dataProvider.length;i++){
		            				selectArray.push(files.dataProvider[i]);
		            			}
		            			files.selectedItems = selectArray;
	            			}
	            		}
            			break;
            			case 'selectinvert':
            			if(event.item.@toggled=='true') { //casting won't seem to work?
	            			if(fileTile.includeInLayout == true) {  
		            			for(i=0;i<fileTile.dataProvider.length;i++){
		            				found = false;
		            				for(j=0; j<fileTile.selectedItems.length; j++) {
		            					if(fileTile.dataProvider[i] == fileTile.selectedItems[j]){
		            						found = true;
		            						break;
		            					}
		            				}
		            				if(found == false) {
		            					selectArray.push(fileTile.dataProvider[i]);
		            				}
	
		            			}
		            			fileTile.selectedItems = selectArray;
	            			}
	            			if(files.includeInLayout == true) {  
		            			for(i=0;i<files.dataProvider.length;i++){
		            				found = false;
		            				for(j=0; j<files.selectedItems.length; j++) {
		            					if(files.dataProvider[i] == files.selectedItems[j]){
		            						found = true;
		            						break;
		            					}
		            				}
		            				if(found == false) {
		            					selectArray.push(files.dataProvider[i]);
		            				}
	
		            			}
		            			files.selectedItems = selectArray;
	            			}
	            		}
            			break;
            		case 'delete':
            			if(event.item.@toggled=='true') { //casting won't seem to work?
	            			var dfile:String = "";
	            			var dfolder:String = foldertree.selectedItem.@path;
	            			if(fileTile.includeInLayout == true) {  
		            			dfile = fileTile.selectedItem.path;
	            			}
	            			if(files.includeInLayout == true) {  
		            			dfile = files.selectedItem.path;
	            			}
	            			trace(dfile);
	            			gateway.call( "files.deleteFile", new Responder(onFileResult, onFault),dfile,dfolder);
	            		}
            			break;
            			case 'rename':
            			if(event.item.@toggled=='true') { //casting won't seem to work?
	            			var rfile:String = "";
	            			var rfolder:String = foldertree.selectedItem.@path;
	            			if(fileTile.includeInLayout == true) {  
		            			rfile = fileTile.selectedItem.name;
	            			}
	            			if(files.includeInLayout == true) {  
		            			rfile = files.selectedItem.name;
	            			}
	            			
							// Create the TitleWindow container.
				            var renameWindow:rename = rename(PopUpManager.createPopUp(this, rename, true));
				            // Add title to the title bar.
				            renameWindow.title="Rename";
				            // Make title bar slightly transparent.
				            renameWindow.setStyle("borderAlpha", 0.9);
							// Add a close button.
				            // To close the container, your must also handle the close event.
							renameWindow.showCloseButton=true;
				            
							renameWindow.rfile = rfile;
							renameWindow.rfolder = foldertree.selectedItem.@path;
							renameWindow.gateway = this.gateway;
							renameWindow.onFileResult = this.onFileResult;
							renameWindow.onFault = this.onFault;
	            		}
            			break;
            		case 'foldercreate':
            		
            			 var createWindow:createFolder = createFolder(PopUpManager.createPopUp(this, createFolder, true));
				            // Add title to the title bar.
				            createWindow.title="Create Folder";
				            // Make title bar slightly transparent.
				            createWindow.setStyle("borderAlpha", 0.9);
				            // Add a close button.
				            // To close the container, your must also handle the close event.
				            createWindow.showCloseButton=true;
				            
							createWindow.path = foldertree.selectedItem.@path;
							createWindow.gateway = this.gateway;
							createWindow.onFileResult = this.onFolderResult;
							createWindow.onFault = this.onFault;
            		break;
            			case 'folderdelete':
            			var dfolder:String = foldertree.selectedItem.@path;
            			gateway.call( "files.deleteFolder", new Responder(onFolderResult, onFault),dfolder);            			
            			break;
            			case 'refresh':
						gateway.call( "files.getFolders", new Responder(onFolderResult, onFault));         			
            			break;
            		default:
            	}   
               /* Alert.show("Label: " + event.item.@label + "\n" + 
                    "Data: " + event.item.@data, "Clicked menu item");*/
            }

            private function zoomTip(val:String):String {
            	return "Zoom "+String(int(val)*2)+"%";;
            }
            private function progressComplete(event:Event):void {
            		//trace("complete loading");
            }
            private function audioplayer(event:ItemClickEvent):void{
            	if(event.index == 0) { //play or pause
            		if(vid.playing == true) {
	            		//mp3player.pause();
	            		soundPlayerBar.dataProvider = ["Play","Stop"];
	            	} else {
	           			mp3player.play();
	           			soundPlayerBar.dataProvider = ["Pause","Stop"];
	           		}
            	}
            	if(event.index == 1) {
            		mp3player.stop();
            		soundPlayerBar.dataProvider = ["Play","Stop"];
            	}
            	
            }
            /*********Video functions***********/
            private function playpausestop(event:ItemClickEvent):void {
            	if(event.index == 0) { //play or pause
            		if(vid.playing == true) {
	            		vid.pause();
	            		playpause.dataProvider = ["Play","Stop"];
	            	} else {
	           			vid.play();
	           			playpause.dataProvider = ["Pause","Stop"];
	           		}
            	}
            	if(event.index == 1) {
            		vid.stop();
            		playpause.dataProvider = ["Play","Stop"];
            	}
            }
           
            private function vidcomplete(): void{
            	playpause.dataProvider = ["Play","Stop"];
            }
			private function vidupdate(event:VideoEvent):void{
				if(vid.totalTime == -1) {//old flv version don't show slidere);
					vidslider.visible = false;
				} else {
					vidslider.visible = true;
					if(vid.bytesLoaded >= vid.bytesTotal) {
						//update the slider
						vidslider.enabled = true;
						vidslider.value = (event.playheadTime/vid.totalTime)*100;
					} else {
						vidslider.enabled = false;
					}
				} 
			}
			private function vidslidedrag():void{
				 if(vid.playing == true) {
            	 	playpause.dataProvider = ["Play","Stop"];
            	 	vid.pause();
            	 }
			}
			private function vidsliderelease():void {
				checkseek();
			}
			private function vidstate(event:VideoEvent):void {
				vidcanseek = event.stateResponsive;
			}
			
			private function vidthumbchange(event:SliderEvent):void {
            	 if(vidcanseek) {
            	 	var time:int = (event.currentTarget.value/100)*vid.totalTime;;
					vid.playheadTime =time;
            	 }
			}
			public function checkseek():void{
            	 if(vidcanseek) {
            	 	var time:int = (vidslider.value/100)*vid.totalTime;;
					vid.playheadTime =time;
            	 } else {
            	 	setTimeout(checkseek,1000);
            	 }
			}
			private function vidchange(event:SliderEvent):void {
			//trace(event.currentTarget.value);
			//trace(vid.totalTime);
			//vid.playheadTime = event.currentTarget.value;
			}
			private function vidtip(val:String):String {
				return String(int(val))+"%";
			}
			
            public function fileClick(event:ListEvent):void
            {
            	var ext:String = event.currentTarget.selectedItem.extension;;
            	if( ext == "jpg" || ext == "gif" || ext == "jpeg") {
          	        imgpreview.includeInLayout = true;
	            	imgpreview.source = "http://flexfm.castlesblog.com/data/"+event.currentTarget.selectedItem.path;	
            		imgpreview.visible = true;
            		pb.source = imgpreview;
            		vidslider.value = 0; //default to 0
            		vidslider.visible = false;
            	} else {
            		imgpreview.visible = false;
	            	imgpreview.includeInLayout = false;
            	}
            	
            	if( ext == "swf") {
          	        swfpreview.includeInLayout = true;	
	            	swf.source = "http://flexfm.castlesblog.com/data/"+event.currentTarget.selectedItem.path;	
            		swfpreview.visible = true;
            		pb.source = swf;
            	} else {
            		swfpreview.visible = false;
	            	swfpreview.includeInLayout = false;
            	}
            	
            	if( ext == "flv") {
          	        flvpreview.includeInLayout = true;
	            	vid.source = "http://flexfm.castlesblog.com/data/"+event.currentTarget.selectedItem.path;	
	            	flvpreview.visible = true;
	            	pb.source = vid;
            	} else {
	            	flvpreview.includeInLayout = false;
	            	flvpreview.visible = false;
	            	if(vid.source != null) {
	            		vid.stop();
	            		vidslider.value = 0;
	            		playpause.dataProvider = ["Play","Stop"];
	            	}
            	}        	
            	
            	if( ext == "txt" || ext == "html") {
          	        txtpreview.includeInLayout = true;	
	            	txtpreview.text = "";	
	            	txtpreview.visible = true;
	            	var txtfile:String =  event.currentTarget.selectedItem.path;
	            	gateway.call( "files.getTXT", new Responder(onTXTResult, onFault),txtfile);
            	} else {
	            	txtpreview.includeInLayout = false;
	            	txtpreview.visible = false;
            	}     
            		
             	if( ext == "mp3") {
          	        soundPlayer.includeInLayout = true;	
	            	soundPlayer.visible = true;
	            	
	            	mp3player.progressBar = pb;
	            	//trace(event.currentTarget.selectedItem.path);
	            	//trace("http://www.flexfm.com.au/data"+foldertree.selectedItem.@path + files.selectedItem.name);
	            	mp3player.load("http://flexfm.castlesblog.com/data"+event.currentTarget.selectedItem.path);
	            	//trace("http://www.mcweb.com.au/files/"+event.currentTarget.selectedItem.path);
	            	//soundE.source = "http://www.mcweb.com.au/files/"+event.currentTarget.selectedItem.path;
            		//pb.source = soundPlayer;
            		//private var playSound:Sound = new Sound();
            		//playSound.url = 
            	} else {
	            	soundPlayer.includeInLayout = false;
	            	soundPlayer.visible = false;
            	}            	   
            }
            public function onTXTResult( result : String ) : void
            {
				txtpreview.text = result;
            }
            public function onFolderResult( result : String ) : void
            {
				folderTree = new XML(result);
				var columns:Array = new Array("name","size","type","modified");
				var folder:String = "../../data/";
				gateway.call( "files.getFiles", new Responder(onFileResult, onFault),"/",columns);
            }
            
            public function onFileResult( result : Array ) : void
            {     	
            	trace("file result");
            	//re-create array objects into bindable objects - Object Proxy
            	var newArray:Array = new Array();
            	for(var i:int=0;i<result.length;i++) {
            		var tmp:ObjectProxy = new ObjectProxy();
            		tmp.name = result[i].name;
            		tmp.icon = result[i].icon;
            		tmp.size = result[i].size;
            		tmp.type = result[i].type;
            		tmp.modified = result[i].modified;
            		tmp.path = result[i].path;
            		tmp.extension = result[i].extension;
            		trace(tmp.icon);
            		newArray.push(tmp);
            	}
            	
            	fileData = newArray;//result;// ArrayUtil.toArray(result);//new ArrayCollection(result);
            	if(filter.text!="") {
            		filterFiles();
            	}
            }

            public function onFault( fault : String ) : void
            {
                trace( fault );
            }
            
            public function treeChanged(event:Event):void {
                var columns:Array = new Array("name","size","type","modified");
				var folder:String = Tree(event.target).selectedItem.@path;
				gateway.call( "files.getFiles", new Responder(onFileResult, onFault),folder,columns);
            }
           public var prevItem:Object;
            public function treeClicked(event:Event):void {
				
					var toggle:Boolean = Tree(event.target).isItemOpen(Tree(event.target).selectedItem);
					if(toggle == true) {
						if(Tree(event.target).selectedItem == prevItem) {
					
						Tree(event.target).expandItem(Tree(event.target).selectedItem, false, true);
						}
					} else {
						Tree(event.target).expandItem(Tree(event.target).selectedItem, true, true);
					}
				
				prevItem = Tree(event.target).selectedItem;
            }
            public function moveFile(event:DragEvent):void {
           // trace(event.);
            }
            
            public function zoomFiles(event:Event):void {
            	files.rowHeight = 25 + zoom.value;
            	files.columns[0].width = 25+ zoom.value;
            	files.columns[1].width = 200+ zoom.value;
            	files.columns[2].width = 100+ zoom.value;
            	files.columns[3].width = 100+ zoom.value;
            	files.setStyle("fontSize",10+(zoom.value/4)); //35 max
            }   
            
            public function displayChange():void {

            	if(changeDisplay.selectedItem.data == "details") {
            		fileTile.includeInLayout = false;  
	            	files.includeInLayout = true;  
	            	fileTile.visible = false;
	            	files.visible = true;
            	}
            	if(changeDisplay.selectedItem.data == "thumbnails") {
            		fileTile.includeInLayout = true;  
	            	files.includeInLayout = false;  
	            	files.visible = false;
	            	fileTile.visible = true;
            	}
            	
            }